﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SmsSyncServer
{
    /// <summary>
    /// Receive 的摘要说明
    /// </summary>
    public class Receive : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        private string GenSimpleSuccessResponse()
        {
            var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
            var m = new { payload = new { success = true, error = (object)null } };
            return ser.Serialize(m);
        }
        private string GenSimpleFailResponse(string Message)
        {
            var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
            var m = new { payload = new { success = false, error = Message } };
            return ser.Serialize(m);
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            var task = context.Request.Params["task"];
            switch (task)
            {
                case "send":

                    break;
                case "sent":
                    break;
                case "result":
                    break;
                default:
                    HandleNewMessage(context);
                    break;
            }

        }

        private void HandleSendRequest(HttpContext context)
        {

        }

        private void HandleNewMessage(HttpContext context)
        {
            var secret = context.Request.Params["secret"].Trim();
            if (Properties.Settings.Default.Secret != secret)
            {
                context.Response.Write(this.GenSimpleFailResponse("Secret code invalid."));
                return;
            }
            var deviceId = context.Request.Params["device_id"].Trim();
            if (deviceId == null)
            {
                context.Response.Write(this.GenSimpleFailResponse("No device id given."));
                return;
            }

            try
            {
                using (var db = new SmsSyncEntities())
                {
                    try
                    {
                        var device = db.Devices.FirstOrDefault(d => d.Code == deviceId);
                        if (device == default(Device))
                        {
                            device = new Device() { Code = deviceId };
                            db.Devices.Add(device);
                            db.SaveChanges();
                        }
                        var uuid = Guid.Parse(context.Request.Params["message_id"]);
                        var message = db.Messages.FirstOrDefault(m => m.UUID == uuid);
                        if (message == default(Message))
                        {
                            message = new Message()
                            {
                                UUID = uuid,
                                From = context.Request.Params["from"],
                                To = context.Request.Params["sent_to"],
                                Content = context.Request.Params["message"],
                                Time = new DateTime(1970, 1, 1, 8, 0, 0) + TimeSpan.FromMilliseconds(double.Parse(context.Request.Params["sent_timestamp"])),
                                Device = device
                            };
                            db.Messages.Add(message);
                            db.SaveChanges();
                        }
                        context.Response.Write(this.GenSimpleSuccessResponse());
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(this.GenSimpleFailResponse("Fail: " + ex.Message));
                    }
                }
            }
            catch
            {
                context.Response.Write(this.GenSimpleFailResponse("Cannot connect db."));
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}